/**
 * 微信公众平台开发模式(JAVA) SDK
 * (c) 2012-2013 ____′↘夏悸 <wmails@126.cn>, MIT Licensed
 * http://www.jeasyuicn.com/wechat
 */
package com.gson;

import java.io.IOException;
import java.io.StringReader;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.xml.parsers.FactoryConfigurationError;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.apache.commons.lang3.StringUtils;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

import com.gson.bean.Articles;
import com.gson.bean.InMessage;
import com.gson.bean.MusicOutMessage;
import com.gson.bean.NewsOutMessage;
import com.gson.bean.OutMessage;
import com.gson.bean.TextOutMessage;
import com.gson.db.MysqlDb;
import com.gson.inf.MessageProcessingHandler;
import com.gson.inter.BaiduMusicService;
import com.gson.inter.BaiduPlaceService;
import com.gson.inter.BaiduWeatherService;
import com.gson.inter.JokeService;
import com.gson.inter.LocateUtil;
import com.gson.inter.RssChild;
import com.gson.inter.RssViewer;
import com.gson.inter.So114Service;
import com.gson.inter.TodayInHistoryService;
import com.gson.inter.XiaoiService;
import com.gson.model.Music;
import com.gson.model.PosInfoModel;
import com.gson.model.Weather;
import com.gson.model.WeatherData;
import com.gson.util.JodaTime;
import com.gson.util.PosInfoHandler;
import com.gson.util.Tools;

/**
 * 自定义实现消息处理
 * @author GodSon
 *
 */
public class MessageProcessingHandlerImpl implements MessageProcessingHandler {

	@Override
	public OutMessage textTypeMsg(InMessage msg) {
		System.out.println("from user==" + msg.getFromUserName());
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		System.out.println("time==" + sdf.format(new Date()));
		System.out.println("content==" + msg.getContent());
		
		TextOutMessage oms = new TextOutMessage();
		StringBuffer replyMsg = new StringBuffer();
		String content = msg.getContent().trim();
		if("?".equals(content)||"？".equals(content)){
			replyMsg.append("欢迎使用微信平台！");
			replyMsg.append("\r\n1、发送：天气+城市");
			replyMsg.append("\r\n\t\t\t 例如'天气上海'");
			replyMsg.append("\r\n\t\t\t 或者'上海天气'");
			replyMsg.append("\r\n2、发送：歌曲+歌名");
			replyMsg.append("\r\n\t\t\t 例如：歌曲存在");
			replyMsg.append("\r\n\t\t\t 或者：歌曲存在@汪峰");
			replyMsg.append("\r\n3、焦点新闻");
			replyMsg.append("\r\n4、历史上的今天");
			replyMsg.append("\r\n5、发送：地区空格关键词");
			replyMsg.append("\r\n\t\t\t 例如'上海 银行'");
			replyMsg.append("\r\n其他、回音壁请直接输入文字信息");
			oms.setContent(replyMsg.toString());
		}else if("3".equals(content)){
			NewsOutMessage nom = new NewsOutMessage();
			List<Articles> articleList = new ArrayList<Articles>();
			String rss_url = "http://news.google.com/news?pz=1&cf=all&ned=cn&hl=zh-CN&output=rss";
			try {
				RssViewer new_viewer = new RssViewer(rss_url);
				ArrayList item_list = new_viewer.getRSS_items();
				Iterator itx = item_list.iterator();

				while (itx.hasNext()) {
					Articles articles = new Articles();
					RssChild rsschild = (RssChild) itx.next();
					articles.setTitle(rsschild.getTitle());
					String link = rsschild.getLink();
					link = link.substring(link.indexOf("&url=")+5);
					articles.setUrl(link);
					
					articleList.add(articles);
				}
			} catch (Exception e) {
				// TODO: handle exception
			}
			
			nom.setArticles(articleList);
			nom.setFuncFlag(0);
			return nom;
		}else if("4".equals(content)){
			String info = TodayInHistoryService.getTodayInHistoryInfo();
			oms.setContent(info);
		}else if(Tools.checkCNet(content)){
			content = content.replaceAll("-", "");
			LocateUtil util = new LocateUtil();
			PosInfoModel posInfo = null;
			
			NewsOutMessage nom = new NewsOutMessage();
			
			String sql = "select * from my_location t where tel = '" + content + "' " +
					"and timediff(now(), create_time) < '00:15' order by id desc ";
			posInfo = getDbLocation(sql);
			if(posInfo!=null) {
				//返回15分钟内的位置信息
				nom = new NewsOutMessage();
				List<Articles> articleList = util.getTencentMap(posInfo, content);
				nom.setArticles(articleList);
				nom.setFuncFlag(0);
				return nom;
			} else {
				try {
					//调用定位接口
					String rtnXml = util.getMobileLocateInfo(content);
					if(StringUtils.isEmpty(rtnXml)){
						oms.setContent("\ue401定位结果为空");
						return oms;
					}
					
					posInfo = util.getPosInfo(rtnXml);
					
					if(posInfo==null) {
						oms.setContent("\ue403定位结果为NULL");
						return oms;
					} else if(posInfo.isErrorFlag()==true){
						//只为一人打造
						if("obaWJuEra0bLBOzgICiUgs7Imzdg".equals(msg.getFromUserName()) && "18930823570".equals(content)) {
							int rand = (int) (Math.random() * 77 %3);
							if(rand==1) {
								oms.setContent(content + "已经乘坐\ue10d回\ue04c了\ue11b");
							} else if(rand==2) {
								oms.setContent("\ue32e天涯咫尺,"+content+"就在你的\ue327里.因为想你时你在\ue022间");
							} else {
								//二次定位后失败,获取数据库中存储的位置信息
								sql = "select * from my_location t where tel = '18930823570' " +
										" order by id desc ";
								posInfo = getDbLocation(sql);
								if(posInfo!=null) {
									nom = new NewsOutMessage();
									List<Articles> articleList = util.getTencentMap(posInfo, content + " " + posInfo.getCreateTime() + " ");
									nom.setArticles(articleList);
									nom.setFuncFlag(0);
									return nom;
								} else {
									oms.setContent("\ue01e" + content + "正在向你\ue115");
									return oms;
								}
							}
						} else {
							oms.setContent("\ue411我也不知道他在哪里！");
							return oms;
						}
						
						
						
					} else {
						//记录到数据库中
						insertMyLocation(content, posInfo.getLATITUDE(), posInfo.getLONGITUDE());
						
						nom = new NewsOutMessage();
						List<Articles> articleList = util.getTencentMap(posInfo, content);
						
						nom.setArticles(articleList);
						nom.setFuncFlag(0);
						return nom;
					}
				} catch (Exception e) {
					// TODO: handle exception
				}
			}
			
		// 如果以“歌曲”2个字开头
		}else if (content.startsWith("歌曲")) {
			// 将歌曲2个字及歌曲后面的+、空格、-等特殊符号去掉  
            String keyWord = content.replaceAll("^歌曲[\\+ ~!@#%^-_=]?", "");
            // 如果歌曲名称为空  
            if ("".equals(keyWord)) {  
            	oms.setContent(getUsage());
            } else {  
                String[] kwArr = keyWord.split("@");  
                // 歌曲名称  
                String musicTitle = kwArr[0];  
                // 演唱者默认为空  
                String musicAuthor = "";  
                if (2 == kwArr.length)  
                    musicAuthor = kwArr[1];  

                // 搜索音乐  
                Music music = BaiduMusicService.searchMusic(musicTitle, musicAuthor);  
                // 未搜索到音乐  
                if (null == music) {  
                    oms.setContent("对不起，没有找到你想听的歌曲<" + musicTitle + ">。");
                } else {  
                    // 音乐消息  
                	MusicOutMessage mom = new MusicOutMessage();
        			
        			mom.setMusic(music);
        			mom.setFuncFlag(0);
        			return mom;
                }  
            } 
         // 如果以“天气”2个字开头
        }else if (content.startsWith("天气") || content.endsWith("天气")) {
        	// 将天气2个字及天气后面的+、空格、-等特殊符号去掉  
            String keyWord = content.replaceAll("^天气[\\+ ~!@#%^_=]?", "").trim();
            if(keyWord.indexOf("天气")>=0){
            	keyWord = content.replaceAll("[-\\+ ~!@#%^_=]?天气$", "").trim();
            }
            // 如果城市名称为空  
            if ("".equals(keyWord)) {  
            	oms.setContent(getWeatherUsage());
            } else {
            	// 搜索天气  
            	Weather weather = BaiduWeatherService.searchWeather(keyWord);
            	if("success".equals(weather.getStatus())) {
            		List<WeatherData> weatherDataList = weather.getResults();
            		if(weatherDataList!=null && weatherDataList.size()>0) {
            			NewsOutMessage nom = new NewsOutMessage();
            			List<Articles> articleList = new ArrayList<Articles>();
    					
    					Articles articles = null;
    					StringBuilder sb = null;
    					for (int i = 0; i < weatherDataList.size(); i++) {
    						articles = new Articles();
    						
    						sb = new StringBuilder();
            				sb.append(weatherDataList.get(i).getDate());
            				sb.append(weatherDataList.get(i).getTemperature());
            				sb.append(weatherDataList.get(i).getWeather());
            				sb.append(weatherDataList.get(i).getWind());
            				articles.setTitle(sb.toString());
            				
            				if(i==0) {
            					int hour = JodaTime.getHour();
                				if(hour>5 && hour<18) {
                					articles.setPicUrl(weatherDataList.get(i).getDayPictureUrl());
                				} else {
                					articles.setPicUrl(weatherDataList.get(i).getNightPictureUrl());
                				}
            				} else {
            					articles.setPicUrl(weatherDataList.get(i).getDayPictureUrl());
            				}
            				
            				articleList.add(articles);
						}
            			
            			nom.setArticles(articleList);
    					nom.setFuncFlag(0);
            			return nom;
            		} else {
            			oms.setContent(getWeatherUsage());
            		}
            	} else {
            		oms.setContent(getWeatherUsage());
            	}
            	
            }
		} else if (content.indexOf(" ") >= 0) {
			String[] word = content.split(" ");
			
			So114Service so114Service = new So114Service();
			String result = so114Service.doSearch(content);
			
			if(StringUtils.isNotEmpty(result)) {
				oms.setContent(result);
			} else {
				oms.setContent(getOrgSearchUsage());
			}

		} else if (content.indexOf("笑话") >= 0) {
			oms.setContent(JokeService.getJoke());
		} else {
			XiaoiService robot = new XiaoiService();
			oms.setContent(robot.getXiaoiInfo(content));
		}
		return oms;
	}

	/**
	 * @param sql
	 * @return
	 */
	private PosInfoModel getDbLocation(String sql) {
		PosInfoModel posInfo = null;
		try {
			MysqlDb db = new MysqlDb();
			ResultSet rs = db.search(sql);
			if(rs!=null) {
				while(rs.next()) {
					posInfo = new PosInfoModel();
					posInfo.setLATITUDE(rs.getString("LOCATION_X"));
					posInfo.setLONGITUDE(rs.getString("LOCATION_Y"));
					posInfo.setCreateTime(rs.getString("CREATE_TIME"));
					break;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return posInfo;
	}



	@Override
	public OutMessage locationTypeMsg(InMessage msg) {
		NewsOutMessage nom = new NewsOutMessage();
		LocateUtil util = new LocateUtil();
		//本人发送才记录数据库
		if("obaWJuPeFxdj9KHgarA6_ny6pRSU".equals(msg.getFromUserName())) {
			insertMyLocation("18930823570", msg.getLocation_X(), msg.getLocation_Y());
		}
		PosInfoModel posInfo = new PosInfoModel();
		posInfo.setLATITUDE(msg.getLocation_X());
		posInfo.setLONGITUDE(msg.getLocation_Y());
		List<Articles> articleList = util.getTencentMap(posInfo, msg.getLabel());
		nom.setArticles(articleList);
		nom.setFuncFlag(0);
		return nom;
	}

	/**
	 * content 电话号码
	 * x LATITUDE 地理位置维度 例如23.134521
	 * y LONGITUDE 地理位置经度 例如113.358803
	 */
	private void insertMyLocation(String content, String x, String y) {
		MysqlDb db = new MysqlDb();
		String sql = "insert into my_location (tel, location_x, location_y, create_time) " +
				"values ('{content}', {location_x}, {location_y}, now())";
		sql = sql.replace("{content}", content);
		sql = sql.replace("{location_x}", x);
		sql = sql.replace("{location_y}", y);
		db.execute(sql);
	}

	@Override
	public OutMessage imageTypeMsg(InMessage msg) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public OutMessage linkTypeMsg(InMessage msg) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public OutMessage eventTypeMsg(InMessage msg) {
		StringBuffer replyMsg = new StringBuffer();
		if("subscribe".equals(msg.getEvent())){
			TextOutMessage oms = new TextOutMessage();
			replyMsg.append("欢迎使用微信平台！");
			replyMsg.append("\r\n1、发送：天气+城市");
			replyMsg.append("\r\n\t\t\t 例如'天气上海'");
			replyMsg.append("\r\n\t\t\t 或者'上海天气'");
			replyMsg.append("\r\n2、发送：歌曲+歌名");
			replyMsg.append("\r\n\t\t\t 例如：歌曲存在");
			replyMsg.append("\r\n\t\t\t 或者：歌曲存在@汪峰");
			replyMsg.append("\r\n3、焦点新闻");
			replyMsg.append("\r\n4、历史上的今天");
			replyMsg.append("\r\n5、发送：地区空格关键词");
			replyMsg.append("\r\n\t\t\t 例如'上海 银行'");
			replyMsg.append("\r\n其他、回音壁请直接输入文字信息");
			oms.setContent(replyMsg.toString());
			return oms;
		}
		return null;
	}

	@Override
	public OutMessage voiceTypeMsg(InMessage msg) {
		// TODO Auto-generated method stub
		return null;
	}
	
	/** 
     * 歌曲点播使用指南 
     *  
     * @return 
     */  
    public static String getUsage() {  
        StringBuffer buffer = new StringBuffer();  
        buffer.append("歌曲点播操作指南").append("\n\n");  
        buffer.append("回复：歌曲+歌名").append("\n");  
        buffer.append("例如：歌曲存在").append("\n");  
        buffer.append("或者：歌曲存在@汪峰").append("\n\n");  
        buffer.append("回复“?”显示主菜单");  
        return buffer.toString();  
    } 
    
	/** 
     * 歌曲查询使用指南 
     *  
     * @return 
     */  
    public static String getWeatherUsage() {  
        StringBuffer buffer = new StringBuffer();  
        buffer.append("天气查询操作指南").append("\n\n");  
        buffer.append("回复：天气+城市").append("\n");  
        buffer.append("例如：天气北京").append("\n");  
        buffer.append("或者：北京天气").append("\n");  
        buffer.append("回复“?”显示主菜单");  
        return buffer.toString();  
    } 
    
	/** 
     * 歌曲查询使用指南 
     *  
     * @return 
     */  
    public static String getOrgSearchUsage() {  
        StringBuffer buffer = new StringBuffer();  
        buffer.append("商家查询操作指南").append("\n\n");  
        buffer.append("发送：地区空格关键词").append("\n");  
        buffer.append("例如：上海 银行").append("\n");  
        buffer.append("回复“?”显示主菜单");  
        return buffer.toString();  
    } 

}
